import puppeteer from "../../../lib/puppeteer/puppeteer.js";
import {
    getGroupPlayerList,
    getPlayerData,
    PLUGIN_PATH
} from "../function/function.js";

export class Rankings extends plugin {
    constructor() {
        super({
            name: '[Sm]排行榜',
            dsc: '查看仆人身价和资金排行榜',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]仆人(身价|资金)排行榜$/, fnc: 'showRankings' }
            ]
        })
    }

    async showRankings(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];
        const type = e.msg.includes('身价') ? 'value' : 'currency';

        const playerList = await getGroupPlayerList(ID[1]);
        const rankings = [];

        for (const playerId of playerList) {
            const playerData = await getPlayerData(ID[1], playerId.replace('.json', ''));
            rankings.push({ id: playerId.replace('.json', ''), value: playerData[type] });
        }

        rankings.sort((a, b) => b.value - a.value);

        const topRankings = rankings.slice(0, 15);
        const info = topRankings.map((player, index) => ({
            rank: index + 1,
            id: player.id,
            value: player.value
        }));

        const image = await puppeteer.screenshot('排行榜', {
            tplFile: 'plugins/Slave-Market/resources/html/rankings/index.html',
            filePath: `${PLUGIN_PATH}/resources/`,
            info,
            type: type === 'value' ? '身价' : '资金'
        });

        return e.reply([image]);
    }
}
